package com.example.demotest.controller;

import com.example.demotest.pojo.User;
import com.example.demotest.repository.UserRepository;
import com.example.demotest.service.UserFollowService;
import com.example.demotest.util.JWT;
import com.example.demotest.pojo.ResponseMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user/follow")
public class UserFollowController {

    @Autowired
    private UserFollowService userFollowService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JWT jwt;

    /**
     * 关注某人
     */
    @PostMapping("/{targetId}")
    public ResponseMessage<String> followUser(HttpServletRequest request, @PathVariable Integer targetId) {
        String token = jwt.extractToken(request);
        if (!isValidToken(token)) return ResponseMessage.error(401, "请先登录");

        Integer userId = jwt.getUserIdFromToken(token);
        if (userId.equals(targetId)) {
            return ResponseMessage.error(400, "不能关注自己");
        }

        boolean success = userFollowService.follow(userId, targetId);
        return success ? ResponseMessage.success("关注成功") : ResponseMessage.error(400, "已关注或操作失败");
    }

    /**
     * 取消关注
     */
    @DeleteMapping("/{targetId}")
    public ResponseMessage<String> unfollowUser(HttpServletRequest request, @PathVariable Integer targetId) {
        String token = jwt.extractToken(request);
        if (!isValidToken(token)) return ResponseMessage.error(401, "请先登录");

        Integer userId = jwt.getUserIdFromToken(token);
        boolean success = userFollowService.unfollow(userId, targetId);
        return success ? ResponseMessage.success("取消关注成功") : ResponseMessage.error(400, "操作失败");
    }

    private boolean isValidToken(String token) {
        return token != null && jwt.validateToken(token);
    }

    /**
     * 获取我的关注列表
     */
    @GetMapping("/following")
    public ResponseMessage<List<Map<String, Object>>> getFollowingList(HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);
        List<User> following = userFollowService.getFollowing(userId);

        // 将 User 转换为 Map，统一格式（与 followers 一致）
        List<Map<String, Object>> result = following.stream().map(user -> {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getUserId());
            map.put("userName", user.getUserName());
            map.put("nickname", user.getNickname());
            map.put("avatar", user.getAvatarUrl());
            map.put("isFollowed", true); // 自己关注的列表默认都是 true
            return map;
        }).collect(Collectors.toList());

        return ResponseMessage.success(result);
    }


    /**
     * 获取我的粉丝列表
     */
    @GetMapping("/followers")
    public ResponseMessage<List<Map<String, Object>>> getFollowersList(HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        // 获取当前用户实体
        User me = userRepository.findById(userId).orElse(null);
        if (me == null) {
            return ResponseMessage.error(404, "用户不存在");
        }

        // 获取粉丝列表（谁关注了我）
        List<User> followers = userFollowService.getFollowers(userId);

        // 获取我关注的人（即我 follow 的用户们）
        List<User> myFollowings = userFollowService.getFollowing(userId);
        Set<Integer> myFollowingIds = myFollowings.stream()
                .map(User::getUserId)
                .collect(Collectors.toSet());

        // 返回结果：粉丝列表 + 是否关注
        List<Map<String, Object>> result = followers.stream().map(user -> {
            Map<String, Object> map = new HashMap<>();
            map.put("userId", user.getUserId()); // ✅ 正确的方法
            map.put("userName", user.getUserName());
            map.put("nickname", user.getNickname());
            map.put("avatar", user.getAvatarUrl());
            map.put("isFollowed", myFollowingIds.contains(user.getUserId()));
            return map;
        }).collect(Collectors.toList());

        return ResponseMessage.success(result);
    }


    /**
     * 是否已关注
     */
    @GetMapping("/is-following/{targetId}")
    public ResponseMessage<Boolean> isFollowing(HttpServletRequest request, @PathVariable Integer targetId) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }
        Integer userId = jwt.getUserIdFromToken(token);
        boolean result = userFollowService.isFollowing(userId, targetId);
        return ResponseMessage.success(result);
    }

    @GetMapping("/check/{targetId}")
    public ResponseMessage<Boolean> checkFollowStatus(
            @PathVariable Integer targetId,
            HttpServletRequest request) {
        String token = jwt.extractToken(request);
        if (token == null || !jwt.validateToken(token)) {
            return ResponseMessage.error(401, "请先登录");
        }

        Integer userId = jwt.getUserIdFromToken(token);

        // 获取当前用户实体
        User me = userRepository.findById(userId).orElse(null);
        if (me == null) {
            return ResponseMessage.error(404, "用户不存在");
        }

        // 获取目标用户实体
        User targetUser = userRepository.findById(targetId).orElse(null);
        if (targetUser == null) {
            return ResponseMessage.error(404, "目标用户不存在");
        }

        // 检查是否已关注
        boolean isFollowing = userFollowService.isFollowing(userId, targetId);
        
        return ResponseMessage.success(isFollowing);
    }
}
